import 'dart:io';

import 'package:webview_flutter/webview_flutter.dart';
import 'package:flutter/material.dart';

const CATCH_URLS = ['m.ctrip.com/', 'm.ctrip.com/html5/', 'm.ctrip.com/html5'];

class MyWebView extends StatefulWidget {
  String? url;
  final String? statusBarColor;
  final bool? hideAppBar;
  final bool? backForbid;
  String? title;

  MyWebView(
      {this.url,
      this.statusBarColor,
      this.hideAppBar = false,
      this.backForbid = false,
      this.title}) {
    if (url != null && url!.contains('ctrip.com')) {
      //fix 携程H5 http://无法打开问题
      url = url!.replaceAll("http://", 'https://');
    }
  }

  @override
  _MyWebViewState createState() => _MyWebViewState();
}

class _MyWebViewState extends State<MyWebView> {

  //是否在list里有这个页面
  _isToMain(String? url) {
    bool contain = false;
    for (var value in CATCH_URLS) {
      if (url?.endsWith(value) ?? false) {
        contain = true;
        break;
      }
    }
    return contain;
  }

  @override
  Widget build(BuildContext context) {
    String statusBarColorStr = widget.statusBarColor ?? '000000';
    Color backButtonColor;
    if (statusBarColorStr == '000000') {
      backButtonColor = Colors.white;
    } else {
      backButtonColor = Colors.black;
    }
    return Scaffold(
      body: Column(
        children: [
          _app_bar(
              Color(int.parse('0xff' + statusBarColorStr)), backButtonColor),
          Expanded(
              child: WebView(
            javascriptMode: JavascriptMode.unrestricted,
            initialUrl: widget.url,
            navigationDelegate: (NavigationRequest request) {
              //返回到指定页面
              if (_isToMain(request.url)) {
                Navigator.pop(context);
                return NavigationDecision.prevent;
              }
              return NavigationDecision.navigate;
            },
          ))
        ],
      ),
    );
  }

  @override
  void dispose() {

    super.dispose();
  }

  _app_bar(Color parse, Color backButtonColor) {
    if (widget.hideAppBar ?? false) {
      return Container(
        color: parse,
        height: 30,
      );
    }
    return Container(
      color: parse,
      padding: const EdgeInsets.only(top: 40, bottom: 10),
      child: FractionallySizedBox(
          widthFactor: 1,
          child: Stack(children: [
            GestureDetector(
              onTap: () {
                Navigator.pop(context);
              },
              child: Container(
                margin: const EdgeInsets.only(left: 10),
                child: Icon(
                  Icons.close,
                  color: backButtonColor,
                  size: 28,
                ),
              ),
            ),
            Positioned(
                child: Center(
              child: Text(
                widget.title ?? '',
                style: TextStyle(color: backButtonColor, fontSize: 20),
              ),
            ))
          ])),
    );
  }
}
